package com.frxuexi.base.mvvm

import android.app.DatePickerDialog
import android.app.DatePickerDialog.OnDateSetListener
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.DatePicker
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType
import java.text.SimpleDateFormat
import java.util.Calendar

abstract class BaseActivity<VDB : ViewDataBinding, VM : BaseViewModel> : AppCompatActivity() {
    //获取当前类的泛型参数列表
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }

    protected val vm: VM by lazy {
//        读取第二个泛型参数
        val clazz = type[1] as Class<VM>
//        根据传入的ViewModel获取对应的ViewModel类型
        ViewModelProvider(this)[clazz]
    }

    protected val binding by lazy {
        //        读取第一个泛型参数
        val clazz = type[0] as Class<VDB>
        //通过反射获取LayoutInflater类里面的inflate方法
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        //反射执行上面获取的方法
        method.invoke(null, layoutInflater) as VDB
    }

    fun onError(t: Throwable) {
        Log.i("===", t.message.toString())
        t.printStackTrace()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        vm.onFailed.observe(this, ::onError)
        initView()
        initData()
    }

    abstract fun initData()

    abstract fun initView()

    fun showDateDialog(tv:TextView){
        val calendar = Calendar.getInstance()
        DatePickerDialog(this,object :OnDateSetListener{
            override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
               tv.text="$year-${month+1}-$dayOfMonth"
            }
        },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show()
    }

    fun getDataTime(time:Long):String{
        return SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time)
    }

    fun getDataTimeT(time:Long):String{
        return SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(time)

    }

    fun getDate(time:Long):String{
        return SimpleDateFormat("yyyy-MM-dd").format(time)
    }

    fun getTime(time:Long):String{
        return SimpleDateFormat("HH:mm:ss").format(time)
    }
}